// pages/Riders/RiderOrders/RiderOrders.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryGoodsRiderOrder , riderUpdateOperationOrderStatus , updateRiderInfo , queryGoodsRiderOrderSts } from '../../../api/riders';
import { queryGoodsDeliveryTime } from '../../../api/goods';
import { throttle } from '../../../utils/util';
const regeneratorRuntime = require('../../../common/runtime');
var QQMapWX = require('../../../common/qqmap-wx-jssdk.min.js');
var qqmapsdk;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    tabNavTop: app.globalData.CustomBar,
    soltMarginRight: app.globalData.soltMarginRight,
    navBgColor: '#FFFFFF',
    orderStatus: '2',
    isUrgent: '', // 是否加急
    tabList: [
      { id: '2', name: '配送中', isUrgent: ''},{ id: '2', name: '加急', isUrgent: '1'},{ id: '1', name: '待取货', isUrgent: ''},{ id: '4', name: '已完成', isUrgent: ''},
    ],
    active: '',
    page: 0,
    total: 0, // 订单总数
    loading: true,
    noMore: false,
    loadingFailed: false,
    isReachBottom: false,
    dataList: [],
    parvince: '上海市',
    takeTotal: 0,
    num: 0,
    show: false,
    riderName: wx.getStorageSync('riderName'),
    todayOrderQuantity: 0, // 今日单量
    totalOrderQuantity: 0, // 累计单量
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key: 'MEZBZ-6D3O4-JPJU6-XRZRL-LH73V-PYFUZ'
    });
    this._queryGoodsRiderOrder();
    this.getUserAddress();
    this._queryGoodsRiderOrderSts();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if(this.data.timeIntervalSeveral){
      clearTimeout(this.data.timeIntervalSeveral);
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      dataList: [],
    })
    this._queryGoodsRiderOrder();
    this._queryGoodsRiderOrderSts();
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: throttle(function(){
    console.log('上拉加载')
    if(this.data.isReachBottom){
      this._queryGoodsRiderOrder()
    }
  },1500),

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 获取订单列表
  _queryGoodsRiderOrder(){
    let _this = this;
    queryGoodsRiderOrder({orderStatus: _this.data.orderStatus,page: _this.data.page,isUrgent: _this.data.isUrgent})
    .then(async res => {
      if(res.success){
        var list = _this.data.dataList;
        for (let index = 0; index < res.data.content.length; index++) {
          const item = res.data.content[index];
          item.goodsInfo = JSON.parse(item.goodsInfo);
          item.receivingAddressInfo = JSON.parse(item.receivingAddressInfo);
          if(item.orderStatus != '4' && item.receivingAddressInfo){
            var deliveryTime = await _this._queryGoodsDeliveryTime(item.receivingAddressInfo.province,item.receivingAddressInfo.city,item.receivingAddressInfo.area);
            item.deliveryTime = deliveryTime;
          }
        }
        if(_this.data.page == 0){
          list = res.data.content;
        }else{
          list = list.concat(res.data.content);
        }
        console.log(list,'list')
        _this.setData({
          dataList: list,
          total: res.data.totalElements,
          page: _this.data.page+1,
        })
        if(_this.data.orderStatus == '2'){
          _this.setData({
            takeTotal: res.data.total,
          })
        }
        if(_this.data.page * 10 >= res.data.totalElements){
          _this.setData({
            isReachBottom: false,
            noMore: true,
            loading: false,
            loadingFailed: false,
          })
        }else{
          _this.setData({
            isReachBottom: true,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取商品配送时间
  _queryGoodsDeliveryTime(province,city,area){
    return new Promise((resolve,reject) => {
      queryGoodsDeliveryTime({province: province,city: city,area: area})
      .then(res => {
        if(res.success){
          resolve(res.data)
        }else{
          reject(res.errMessage)
        }
      })
    })
  },
  // tab切换
  onChange(e){
    console.log(e)
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
      active: e.detail.name,
      isUrgent: this.data.tabList[e.detail.index].isUrgent,
      orderStatus: this.data.tabList[e.detail.index].id,
      dataList: [],
    })
    this._queryGoodsRiderOrder();
  },
  // 一键取货
  allTakeGoods(){
    let _this = this;
    wx.showModal({
      title: '一键取货',
      content: `确认共${_this.data.total}件包裹已全部取货，确认后无法恢复`,
      success: (modal)=>{
        if(modal.confirm){
          _this._riderUpdateOperationOrderStatus({orderStatus: '2'});
        }
      }
    })
  },
  // 联系店家
  callUser(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    wx.makePhoneCall({
      phoneNumber: item.receivingAddressInfo.receiverPhone,
    })
  },
  // 确认送达
  subAccomplish(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    this._riderUpdateOperationOrderStatus({orderCode: item.orderCode,orderStatus: '3'});
  },
  // 确认取货
  subTakeGoods(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    this._riderUpdateOperationOrderStatus({orderCode: item.orderCode,orderStatus: '2'});
  },
  // 骑手操作订单
  _riderUpdateOperationOrderStatus({orderCode,orderStatus}){
    let _this = this;
    riderUpdateOperationOrderStatus({orderCode: orderCode,orderStatus: orderStatus})
    .then(res => {
      if(res.success){
        _this.setData({
          page: 0,
          isReachBottom: false,
          noMore: false,
          loading: false,
          loadingFailed: false,
        })
        _this._queryGoodsRiderOrder();
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 定位
  getUserAddress(e){
    var _this = this;
    wx.getSetting({
      success: (res) => {
        console.log(res,'res')
        if(res.authSetting['scope.userLocation']){
          _this._getLocation();
        }else{
          wx.authorize({
            scope: 'scope.userLocation',
            success: ()=>{
              console.log(e,'e')
              _this._getLocation();
            },
            fail: (err) => {
              console.log(err,'err')
              wx.showModal({
                title: '获取定位信息',
                content: '请允许获取您的位置信息，否则小程序部分功能将无法使用',
                success: (res) => {
                  if(res.confirm){
                    wx.openSetting({
                      success: (res) => {
                        if(res.authSetting['scope.userLocation']){
                          _this._getLocation();
                        }
                      },
                    })
                  }
                }
              })
            }
          })
        }
      }
    })
  },
  // 选择地图定位
  _getLocation(){
    console.log('定位')
    let _this = this;
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log(res,'位置信息')
        const latitude = res.latitude
        const longitude = res.longitude
        if(_this.data.num == 0){
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: latitude,
              longitude: longitude,
            },
            success: (res) => {
              console.log(res,'res')
              res = res.result;
              _this.setData({
                province: res.address_component.province,
                num: _this.data.num+1,
              })
            }
          })
        }
        // 上传骑手位置
        _this.updateRiderAddress({lat: latitude,lgt: longitude});
        // 定时器
        if(_this.data.takeTotal > 0){
          var timeIntervalSeveral = setTimeout(_this._getLocation, 180000);
          _this.setData({
            timeIntervalSeveral,
            timeList,
          })
        }else{
          if(_this.data.timeIntervalSeveral){
            clearTimeout(_this.data.timeIntervalSeveral); //清除定时器
          }
        }
      },
      fail: (err) => {
        console.log(err,'err')
      }  
    })
  },
  // 页面跳转
  goNext(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    // console.log(JSON.stringify(item))
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
        })
      }
    }
  },
  // 骑手保存地理位置
  updateRiderAddress({lat,lgt}){
    let _this = this;
    var userId = wx.getStorageSync('riderUserId');
    updateRiderInfo({userId: userId,latitude:lat,longitude:lgt})
    .then(res => {
      if(res.success){

      }else{
        wx.showToast({
          title: res.errMessage,
          icon:'none',
        })
      }
    })
  },
  // 刷新订单
  resetData(){
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
    })
    this._queryGoodsRiderOrder();
    this._queryGoodsRiderOrderSts();
    wx.showToast({
      title: '已刷新',
      icon: 'none',
    })
  },
  // 个人中心
  showUser(){
    this.setData({
      show: true,
    })
  },
  onClose(){
    this.setData({
      show: false,
    })
  },
  // 获取骑手配送订单统计
  _queryGoodsRiderOrderSts(){
    let _this = this;
    queryGoodsRiderOrderSts()
    .then(res => {
      if(res.success){
        _this.setData({
          'todayOrderQuantity': res.data.todayOrderQuantity, // 今日单量
          'totalOrderQuantity': res.data.totalOrderQuantity, // 累计单量
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 返回
  back(){
    wx.navigateBack({
      delta: 2,
    })
  },
})